package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.OrderNumberGenerator;
import com.ruoyi.system.domain.BdmBalanceChange;
import com.ruoyi.system.domain.BdmTopupRecord;
import com.ruoyi.system.domain.BdmUser;
import com.ruoyi.system.domain.dto.BdmTopupRecordDto;
import com.ruoyi.system.domain.vo.BdmTopupRecordVo;
import com.ruoyi.system.domain.vo.StatisticsTopupRecordVo;
import com.ruoyi.system.mapper.BdmTopupRecordMapper;
import com.ruoyi.system.service.IBdmBalanceChangeService;
import com.ruoyi.system.service.IBdmTopupRecordService;
import com.ruoyi.system.service.IBdmUserService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 提现记录Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-20
 */
@Service
public class BdmTopupRecordServiceImpl implements IBdmTopupRecordService
{
    @Autowired
    private BdmTopupRecordMapper bdmTopupRecordMapper;

    @Autowired
    private IBdmUserService iBdmUserService;

    @Autowired
    private IBdmBalanceChangeService iBdmBalanceChangeService;

    @Autowired
    private ISysUserService iSysUserService;

    /**
     * 查询提现记录
     *
     * @param id 提现记录主键
     * @return 提现记录
     */
    @Override
    public BdmTopupRecord selectBdmTopupRecordById(Long id)
    {
        return bdmTopupRecordMapper.selectBdmTopupRecordById(id);
    }

    /**
     * 查询提现记录列表
     *
     * @param bdmTopupRecord 提现记录
     * @return 提现记录
     */
    @Override
    public List<BdmTopupRecord> selectBdmTopupRecordList(BdmTopupRecord bdmTopupRecord)
    {
        return bdmTopupRecordMapper.selectBdmTopupRecordList(bdmTopupRecord);
    }

    /**
     * 新增提现记录
     *
     * @param bdmTopupRecordDto 提现记录
     * @return 结果
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public int insertBdmTopupRecord(BdmTopupRecordDto bdmTopupRecordDto)
    {
        Long userId = SecurityUtils.getUserId();
        BdmUser bdmUser = iBdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, userId).one();
        if(bdmUser==null){
            throw new GlobalException("用户不存在");
        }
        if (bdmUser.getRemainingSum().compareTo(bdmTopupRecordDto.getTopupAmount()) < 0){
            throw new GlobalException("余额不足");
        }
        bdmUser.setRemainingSum(bdmUser.getRemainingSum().subtract(bdmTopupRecordDto.getTopupAmount()));
        iBdmUserService.updateById(bdmUser);
        String orderId = OrderNumberGenerator.generateOrderNumber("TX");
        BdmTopupRecord bdmTopupRecord = BeanUtil.copyProperties(bdmTopupRecordDto, BdmTopupRecord.class);
        bdmTopupRecord.setSysUserid(userId)
                .setOrderId(orderId)
                .setStatus("1");
        bdmTopupRecord.setCreateTime(DateUtils.getNowDate());
        bdmTopupRecord.setCreateBy(SecurityUtils.getUsername());
        // 支出
        BdmBalanceChange change = new BdmBalanceChange();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        change.setUserId(user.getUserId());
        change.setUserPhone(user.getPhonenumber());
        change.setNickName(user.getNickName());
        change.setAvatar(user.getAvatar());
        change.setVariation(bdmTopupRecordDto.getTopupAmount().toString());
        change.setVariationBefore(bdmUser.getRemainingSum().toString());
        change.setVariationAfter(bdmUser.getRemainingSum().subtract(bdmTopupRecordDto.getTopupAmount()).toString());
        change.setVariationType(1L);
        change.setAddOrSubtract(2L);
        change.setBusinessType("申请提现");
        iBdmBalanceChangeService.insertBdmBalanceChange(change);
        bdmTopupRecord.setCommission(new BigDecimal("0.008").multiply(bdmTopupRecord.getTopupAmount()).setScale(2, RoundingMode.HALF_UP).toString());
        bdmTopupRecord.setExpectedAmount(new BigDecimal("0.992").multiply(bdmTopupRecord.getTopupAmount()).setScale(2, RoundingMode.HALF_UP).toString());
        return bdmTopupRecordMapper.insertBdmTopupRecord(bdmTopupRecord);
    }

    /**
     * 修改提现记录
     *
     * @param bdmTopupRecord 提现记录
     * @return 结果
     */
    @Override
    public int updateBdmTopupRecord(BdmTopupRecord bdmTopupRecord)
    {
        bdmTopupRecord.setUpdateTime(DateUtils.getNowDate());
        return bdmTopupRecordMapper.updateBdmTopupRecord(bdmTopupRecord);
    }

    /**
     * 提现审核
     * @param bdmTopupRecord
     * @return
     */
    @Override
    public int auditBdmTopupRecord(BdmTopupRecord bdmTopupRecord) {

        bdmTopupRecord.setUpdateTime(DateUtils.getNowDate());
        bdmTopupRecord.setUpdateBy(SecurityUtils.getUsername());
        List<Long> roles = SecurityUtils.getLoginUser().getUser()
                .getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList());
        if (!roles.contains(1L)) {
            throw new GlobalException("请联系管理员审核");
        }
        return bdmTopupRecordMapper.updateBdmTopupRecord(bdmTopupRecord);
    }

    /**
     * 批量删除提现记录
     *
     * @param ids 需要删除的提现记录主键
     * @return 结果
     */
    @Override
    public int deleteBdmTopupRecordByIds(Long[] ids)
    {
        return bdmTopupRecordMapper.deleteBdmTopupRecordByIds(ids);
    }

    /**
     * 删除提现记录信息
     *
     * @param id 提现记录主键
     * @return 结果
     */
    @Override
    public int deleteBdmTopupRecordById(Long id)
    {
        return bdmTopupRecordMapper.deleteBdmTopupRecordById(id);
    }

    /**
     * 提现统计
     * @return
     */
    @Override
    public StatisticsTopupRecordVo statistics() {
        BdmTopupRecordDto bdmTopupRecordDto = new BdmTopupRecordDto();
        bdmTopupRecordDto.setSysUserid(SecurityUtils.getUserId());
        return bdmTopupRecordMapper.statistics(bdmTopupRecordDto);
    }

    /**
     * 提现审核驳回或异常
     * @param bdmTopupRecord
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public boolean reject(BdmTopupRecord bdmTopupRecord) {
        BdmTopupRecord record = bdmTopupRecordMapper.selectBdmTopupRecordById(bdmTopupRecord.getId());
        if (record == null) {
            throw new GlobalException("当前信息不存在");
        }
        record.setStatus(bdmTopupRecord.getStatus());
        bdmTopupRecordMapper.updateBdmTopupRecord(record);
        iBdmUserService.updateUserMone(record.getSysUserid(),record.getTopupAmount());
        return true;
    }

    @Override
    public List<BdmTopupRecordVo> export(BdmTopupRecord bdmTopupRecord) {
        return bdmTopupRecordMapper.export(bdmTopupRecord);
    }

    @Override
    public BdmTopupRecordVo withdrawStatistics() {
        return bdmTopupRecordMapper.withdrawStatistics();
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public boolean rejectNew(List<Long> ids) {
        for (Long id : ids) {
            BdmTopupRecord topupRecord = this.selectBdmTopupRecordById(id);
            if (!topupRecord.getStatus().equals("1")) {
                throw new GlobalException("当前状态不是申请中状态无法操作");
            }
            BdmTopupRecord record = new BdmTopupRecord();
            record.setStatus("4");
            record.setId(id);
            this.reject(record);

            BdmBalanceChange change = new BdmBalanceChange();
            SysUser sysUser = iSysUserService.selectUserById(topupRecord.getSysUserid());
            if (sysUser != null){
                BdmUser user = iBdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, sysUser.getUserId()).one();
                change.setUserId(sysUser.getUserId());
                change.setUserPhone(sysUser.getPhonenumber());
                change.setNickName(sysUser.getNickName());
                change.setAvatar(sysUser.getAvatar());
                change.setVariation(topupRecord.getTopupAmount().toString());
                change.setVariationBefore(user.getRemainingSum().toString());
                change.setVariationAfter(user.getRemainingSum().subtract(topupRecord.getTopupAmount()).toString());
                change.setVariationType(1L);
                change.setAddOrSubtract(1L);
                change.setBusinessType("提现驳回");
                iBdmBalanceChangeService.insertBdmBalanceChange(change);
            }

        }
        return true;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public boolean passNew(List<Long> ids) {
        for (Long id : ids) {
            BdmTopupRecord topupRecord = this.selectBdmTopupRecordById(id);
            if (!topupRecord.getStatus().equals("1")) {
                throw new GlobalException("当前不是申请中状态无法操作");
            }
            BdmTopupRecord record = new BdmTopupRecord();
            record.setStatus("2");
            record.setId(id);
            this.auditBdmTopupRecord(record);
        }
        return true;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public boolean remittance(List<Long> ids) {
        for (Long id : ids) {
            BdmTopupRecord topupRecord = this.selectBdmTopupRecordById(id);
            if (!topupRecord.getStatus().equals("2")) {
                throw new GlobalException("当前状态不是审核通过状态无法操作");
            }
            BdmTopupRecord record = new BdmTopupRecord();
            record.setStatus("3");
            record.setId(id);
            this.updateBdmTopupRecord(record);
        }
        return true;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public boolean error(List<Long> ids) {
        for (Long id : ids) {
            BdmTopupRecord topupRecord = this.selectBdmTopupRecordById(id);
            if (!topupRecord.getStatus().equals("2")) {
                throw new GlobalException("当前状态不是申请中状态无法操作");
            }
            BdmTopupRecord record = new BdmTopupRecord();
            record.setStatus("5");
            record.setId(id);
            this.reject(record);

            BdmBalanceChange change = new BdmBalanceChange();
            SysUser sysUser = iSysUserService.selectUserById(topupRecord.getSysUserid());
            if (sysUser != null){
                BdmUser user = iBdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, sysUser.getUserId()).one();
                change.setUserId(sysUser.getUserId());
                change.setUserPhone(sysUser.getPhonenumber());
                change.setNickName(sysUser.getNickName());
                change.setAvatar(sysUser.getAvatar());
                change.setVariation(topupRecord.getTopupAmount().toString());
                change.setVariationBefore(user.getRemainingSum().toString());
                change.setVariationAfter(user.getRemainingSum().subtract(topupRecord.getTopupAmount()).toString());
                change.setVariationType(1L);
                change.setAddOrSubtract(1L);
                change.setBusinessType("提现异常");
                iBdmBalanceChangeService.insertBdmBalanceChange(change);
            }
        }
        return true;
    }
}
